﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCP_Spy
{
    internal class Socket_Class
    {
        public static string Initial_Value_IP = "10.131.43.167";
        public static string Initial_Value_Port = "6666";

        public static bool socket_stat = false;
        public static bool socket_close_judge = true;

        public static Socket so = null;

        public static bool TCP_Connect(string str_address ,string port)
        {
            so = new Socket(SocketType.Stream, ProtocolType.Tcp); // 实例化
            IPAddress address = IPAddress.Parse(str_address);     // 设置IP
            EndPoint remoteEP = new IPEndPoint(address, int.Parse(port));
            try
            {
                so.Connect(remoteEP);                             // 打开
                socket_stat = true;
                return true;
            }
            catch (Exception)
            {
                socket_stat = false;
                return false;
            }
        }

        public static void socket_close()
        {
            socket_stat = false;
            socket_close_judge= true;
            if (so != null)
                so.Close(100);  // 断开与服务器的连接
        }

        public static void Send(string str)
        { 
            byte[] buffer = System.Text.Encoding.Default.GetBytes(str);
            
            so.Send(buffer);
        }

        public static string Receive()
        {
            byte[] Receive_Data = new byte[1024];
            int len = 0;
            string str = "";

            try
            {
                len = so.Receive(Receive_Data);
                if (len < 1)
                    socket_close();
            }
            catch (Exception){}

            str = System.Text.Encoding.Default.GetString(Receive_Data, 0, len);
            return str;
        }
    }
}
